#!/usr/bin/env python

import poplib
from email import parser
from subprocess import call
import StringIO
import time

if __name__ == "__main__":
	pop_conn = poplib.POP3_SSL('pop.gmail.com')
	pop_conn.user('jtan.mailservice')
	pop_conn.pass_('{E4B7DF43-6AE1-47B2-9B4A-5A96A30FC508}')
	#Get messages from server:
	messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
	# Concat message pieces:
	messages = ['\n'.join(mssg[1]) for mssg in messages]
	#Parse message intom an email object:
	messages = [parser.Parser().parsestr(mssg) for mssg in messages]
	for message in messages:
		cmd = message['subject']
		print('Processing email ' + cmd)
		if cmd == 'getalpha':
			for part in message.walk():
				if part.get_content_type() == 'text/plain':
					content = StringIO.StringIO(part.get_payload())	
					while 1:
						line = content.readline()
						#print('process line ' + line)
						if not line:
							break
						line = line.strip()
						if line.startswith( 'http' ):
							print('Getting ' + line)
							call(['./'+cmd+'.sh', line])
							call(['./sendemail.sh', message['From']])
							time.sleep(1)
					break
				else:
					pass
					#print("not a plain text, skip")
		elif cmd == 'help' or cmd == 'getstockprice':
			call(['./'+cmd+'.sh'])
			call(['./sendemail.sh', message['From']])
		else:
			print('unknown command')

	pop_conn.quit()
